package com.sys.product.exception;

import com.sys.common.exception.BizCodeEnum;
import com.sys.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.sys.product.controller")//指定包
public class MallExceptionAdvice {

    //数据校验异常全局处理
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R handlerValidException(MethodArgumentNotValidException excetion) {
        BindingResult result = excetion.getBindingResult();

        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        log.error("数据校验出现问题:{},异常类型{}", excetion.getMessage(), excetion.getClass());
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", map);
    }

    //其他异常，托底处理
    //@ExceptionHandler(value = Throwable.class)//先关了，容易看报错
    public R handleException(Throwable throwable) {
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }

}
